package com.xytc.company.company_backend.adminEndPoint.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xytc.company.company_backend.adminEndPoint.entity.dao.PackagingBoxDao;
import com.xytc.company.company_backend.adminEndPoint.entity.rto.PackagingBoxRto;
import com.xytc.company.company_backend.adminEndPoint.mapper.IPackagingManageMapper;
import com.xytc.company.company_backend.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/company/packingBoxManage")
public class PackagingBoxManageController {

    @Autowired
    private IPackagingManageMapper packagingManageMapper;

    /**
     * 接口3.1 新增或编辑包装套件信息
     *
     * @param packagingBoxRto
     * @return
     */
    @PostMapping("/addOrUpdatePackagingBox")
    public Result<?> addOrUpdatePackagingBox(@RequestBody PackagingBoxRto packagingBoxRto) {

        PackagingBoxDao packagingBoxDao = new PackagingBoxDao();

        packagingBoxDao.setName(packagingBoxRto.getName());
        packagingBoxDao.setSupplier(packagingBoxRto.getSupplier());
        // 前端传递的货币单位为元，是 float 型，存入db时转换成分，乘以 100
        packagingBoxDao.setSupplierPrice(Float.valueOf(packagingBoxRto.getSupplierPrice() * 100).intValue());
        packagingBoxDao.setSupplierAddress(packagingBoxRto.getSupplierAddress());
        packagingBoxDao.setDetails(packagingBoxRto.getDetails().toJSONString());
        packagingBoxDao.setRemark(packagingBoxRto.getRemark());
        packagingBoxDao.setStatus(1); // 新增包装套件信息时，菜品状态为默认值 1；编辑接口不涉及上架/下架 状态的更改，上架/下架由接口 3.3 来实现
        packagingBoxDao.setDelFlag(0); // del_flag 标记为0；删除店铺由接口3.4 来实现

        if (StringUtils.isBlank(packagingBoxDao.getId())) {
            // 先判断表中是否已经有同名的菜品，不允许添加重复店铺名称的店铺
            List<PackagingBoxDao> list = packagingManageMapper.selectList(
                    new LambdaQueryWrapper<PackagingBoxDao>()
                            .eq(PackagingBoxDao::getId, packagingBoxRto.getId())
                            .eq(PackagingBoxDao::getName, packagingBoxRto.getName()));
            if (list != null && list.size() > 0) {
                return Result.error("包装【"+ packagingBoxRto.getName() + "】已存在，不能录入重复名称的包装套件");
            }
            packagingBoxDao.setCreateTime(new Date()); // 新增包装套件时，创建时间为接口调用时间
            // 菜品id为null或空字符串，新增包装套件
            packagingManageMapper.insert(packagingBoxDao);
        } else {
            packagingBoxDao.setId(packagingBoxRto.getId());
            // 包装套件id不为null，也不为空字符串，更新包装套件
            packagingManageMapper.updateById(packagingBoxDao);
        }

        return Result.ok();
    }


    /**
     * 接口3.2 根据包装套件名查询符合条件的包装套件
     * @param keyword 为null或空字符串，这sql语句中，like "%%"，即不设置过滤条件
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryPackagingBoxByKeyword")
    public Result<?> queryPackagingBoxByKeyword(@RequestParam("keyword") String keyword,
                                        @RequestParam(value = "pageNo", required = false,defaultValue = "1") Integer pageNo,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        Page<PackagingBoxDao> page = new Page<>(pageNo, pageSize);
        Page<PackagingBoxDao> pageList = packagingManageMapper.selectPage(page,
                new LambdaQueryWrapper<PackagingBoxDao>()
                        .eq(PackagingBoxDao::getDelFlag, 0)
                        .like(PackagingBoxDao::getName, keyword));

        JSONArray formatedPackagingBoxList = new JSONArray();
        for(int k = 0 ; k < pageList.getRecords().size(); k ++) {
            PackagingBoxDao packagingBoxDao = pageList.getRecords().get(k);
            JSONObject packaingBox = new JSONObject();

            packaingBox.put("packagingBoxId", packagingBoxDao.getId());
            packaingBox.put("name", packagingBoxDao.getName());
            packaingBox.put("supplier", packagingBoxDao.getSupplier());
            // 将货币单位从分 转换为 元
            packaingBox.put("supplierPrice", (1.0 * packagingBoxDao.getSupplierPrice()) / 100);
            packaingBox.put("supplierAddress", packagingBoxDao.getSupplierAddress());
            packaingBox.put("details", JSONArray.parseArray(packagingBoxDao.getDetails()));
            packaingBox.put("remark", packagingBoxDao.getRemark());
            packaingBox.put("status", packagingBoxDao.getStatus());
            formatedPackagingBoxList.add(packaingBox);
        }

        JSONObject resultData = new JSONObject();
        resultData.put("totalPages", pageList.getPages());
        resultData.put("totalCount", pageList.getTotal());
        resultData.put("currentPage", pageNo);
        resultData.put("packagingBoxList", formatedPackagingBoxList);

        return Result.ok(resultData);
    }

    /**
     * 接口3.3 切换包装套件状态
     * @param packagingBoxId
     * @param status 1 表示上架中；2 表示下架
     * @return
     */
    @PutMapping("/changePackagingBoxState")
    public Result<?> changePackagingBoxState(@RequestParam("packagingBoxId") String packagingBoxId, @RequestParam("status") Integer status) {

        PackagingBoxDao packagingBoxDao = new PackagingBoxDao();
        packagingBoxDao.setId(packagingBoxId);
        packagingBoxDao.setStatus(status);

        try{
            packagingManageMapper.updateById(packagingBoxDao);
            log.info("包装盒{}状态更新成功，成功更新为 {}", packagingBoxId, status);
            return Result.ok("包装盒状态更新成功");
        }catch (Exception ex) {
            log.error("切换包装盒状态失败 {}",ex);
            return Result.error(500,"包装盒状态更新成功");
        }
    }

    /**
     * 接口3.4 删除包装盒
     * @param packagingBoxId
     * @return
     */
    @DeleteMapping("/deletePackagingBox")
    public Result<?> deletePackagingBox(@RequestParam("packagingBoxId") String packagingBoxId){

        PackagingBoxDao packagingBoxDao = new PackagingBoxDao();
        packagingBoxDao.setId(packagingBoxId);
        packagingBoxDao.setDelFlag(1);
        try{
            packagingManageMapper.updateById(packagingBoxDao);
            log.info("包装盒{}删除成功", packagingBoxId);
            return Result.ok("包装盒删除成功");
        }catch (Exception ex) {
            log.error("包装盒删除失败 {}",ex);
            return Result.error(500,"包装盒删除失败");
        }
    }
}
